﻿using Email.Data;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static System.Net.Mime.MediaTypeNames;

namespace Email
{
    public partial class login : Form
    {
        private UserManager _userManager;
        public login()
        {
            InitializeComponent();
            _userManager = new UserManager();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.Hide(); // 隐藏主界面
            RegisterForm registerForm = new RegisterForm(_userManager);
            registerForm.ShowDialog();
            this.Close(); // 注册成功直接跳转了
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Hide(); // 隐藏主界面
            string username = textBox1.Text;
            string password = textBox2.Text;

            try
            {
                if (_userManager.ValidateUser(username, password))
                {
                    string smtp = _userManager.GetSmtpAuthCode(username);
                    if (string.IsNullOrEmpty(smtp)) // 由于失效或者被删除了
                    {
                        MessageBox.Show("数据库里没有SMTP授权码，可能是失效了或者已经删除");
                        RegisterForm registerForm = new RegisterForm(_userManager);
                        registerForm.ShowDialog();

                        // 检查注册表单是否成功更新了SMTP授权码
                        smtp = _userManager.GetSmtpAuthCode(username);
                        if (!string.IsNullOrEmpty(smtp))
                        {
                            MessageBox.Show("注册成功！");
                            Form1 form1 = new Form1(username, smtp, password);
                            form1.ShowDialog();
                            // 更新 textBox 中的内容
                            textBox1.Text = username;
                            textBox2.Text = password;
                        }
                        else
                        {
                            MessageBox.Show("注册失败，未能更新SMTP授权码。");
                        }
                        this.Show(); // 重新显示主界面
                    }
                    else
                    {
                        MessageBox.Show("登录成功！");
                        Form1 form1 = new Form1(username, password, smtp);
                        form1.ShowDialog();
                        this.Close(); // 关闭当前窗口
                    }
                }
                else
                {
                    MessageBox.Show("用户名或密码有问题！");
                    this.Show(); // 重新显示主界面
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"发生错误：{ex.Message}");
                this.Show(); // 重新显示主界面
            }
        }


    }
}
